<template>
    <eui-background type="full">
        <view class="search-view">
            <eui-search-bar
                radius="20"
                placeholder="搜索应用"
                clearButton="none"
                bgColor="rgba(255,255,255, 0.8)"
                v-model="c_search">
                <template #searchFields>
                    <eui-button title="dsafsadf"></eui-button>
                </template>
            </eui-search-bar>
            <!-- 蒙版 -->
            <div class="mask-box">
                <transition name="fade">
                    <view v-show="isPopupVisible" class="fade-popup"  @click="hidePopup" :style="{ height: fadeHeight + 'px'}">
                        <view class="search-popup-main" :style="{'height': popupHeight}" @click="handlePopupMain">
                            <eui-card hPadding="15" vPadding="28" class="search-card" :class="[theme]" @click.stop>
                                <eui-grid :column="4" :showBorder="false" :highlight="false" class="menu-row-bottom" v-if="filterMenuData.length && c_search.length">
                                    <eui-grid-item v-for="k in filterMenuData.slice(0, 8)" :key="k.c_menu_code">
                                        <view class="grid-item-box flex-column-center" @click.stop="onTapMenu(k, 'Quick')">
                                            <view class="img-box flex-row-center" :style="{'background-color': k.c_start_color}">
                                                <image :src="k.c_menu_img" mode="scaleToFill" class="image" @error="imageError(k)" />
                                            </view>
                                            <text class="title ellipsis-line-2">{{ k.c_menu_title }}</text>
                                        </view>
                                    </eui-grid-item>
                                </eui-grid>
                                <view class="tips" v-if="filterMenuData.length > 0 && c_search.length">共搜索到{{filterMenuData.length > 8 ? 8 : filterMenuData.length }}个应用</view>
                                <view class="tips note-data-tips" v-if="filterMenuData.length == 0 && c_search.length">没有搜索到相关的应用哦~</view>
                            </eui-card>
                        </view>
                    </view>
                </transition>
            </div>

            <eui-card vPadding="0" hPadding="0">
                <eui-tab
                    v-if="menuList.length > 4"
                    :tabs="tabData"
                    :spaceLeft="spaceLeft"
                    :value="industryTabIndex"
                    @change="tabChange"
                    showFixed
                    :height="88"
                    :toggleFixed="toggleFixed"
                    @update:toggleFixed="toggleFixed = $event"
                >
                    <template v-slot:icons>
                        <view class="iconfont icon-zhankai" :class="{'iconfontColor': toggleFixed, [theme]: true}"></view>
                    </template>
                </eui-tab>

                <scroll-view
                    scroll-y class="home-content"
                    :style="{height: scrollHeight + 'px'}"
                    :scroll-top="scrollTop"
                    :scroll-with-animation="true"
                    @scroll="throttledScroll"
                >
                    <view v-for="(item, index) in menuList" :key="index" class="menu">
                        <text class="menu-module ellipsis-line-2">{{ item.c_menu_title }}</text>
                        <view class="menu-row-top flex-row" v-if=" item.modelsTop.length > 0">
                            <view
                                v-for="j in item.modelsTop"
                                :key="j.c_menu_code"
                                @click="onTapMenu(j)"
                                class="menu-item"
                            >
                                <view class="flex-row menu-row-2" :style="{'background-color': j.c_start_color}">
                                    <view class="img-box">
                                        <image :src="j.c_menu_img" mode="scaleToFill" class="image" @error="imageError(j)"/>
                                    </view>
                                    <view class="right-box">
                                        <text class="title ellipsis-line-2">{{ j.c_menu_title }}</text>
                                        <text class="description text-ellipsis">{{ j.c_menu_title }}</text>
                                    </view>
                                </view>

                            </view>
                        </view>
                        <eui-grid :column="4" :showBorder="false" :highlight="false" class="menu-row-bottom" v-if="item.modelsBottom.length > 0">
                            <eui-grid-item v-for="k in item.modelsBottom" :key="k.c_menu_code">
                                <view class="grid-item-box flex-column-center" @click="onTapMenu(k)">
                                <view class="img-box flex-row-center" :style="{'background': k.c_start_color}">
                                    <image :src="k.c_menu_img" mode="scaleToFill" class="image" @error="imageError(k)" />
                                </view>
                                <text class="title ellipsis-line-2">{{ k.c_menu_title }}</text>
                                </view>
                            </eui-grid-item>
                        </eui-grid>
                    </view>
                </scroll-view>
            </eui-card>
        </view>
        <CustomTabBar current="应用"/>
    </eui-background>
</template>


<script setup lang="ts">
import { storeToRefs } from 'pinia';
import service from '../../../common/service';
import { ref, nextTick, computed, watch } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from '../../../store/modules/store';
import { hexToRgb, hexToRgbToLinear } from '@/hooks/useUtils';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { useThemeStore } from '@/store/themeStore';
import { init, clearRdsLocalStorage } from '@/hooks/init';
import { useModuleDataStore } from '@/store/useModuleDataStore';
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);


const mainStore = useMainStore();
const scrollHeight = ref(1000);
const scrollTop = ref(0); // 用于控制 scroll-into-view
const initTop = ref(0); // 用于控制 scroll-into-view
const toggleFixed = ref(false);
/**
 * tabs
 */
const tabData = ref([]);
const industryTabIndex = ref(0);
const spaceLeft = ref(0);
const tabChange = (e) => {
    toggleFixed.value = false;
    industryTabIndex.value = e;
    nextTick(() => {
        setTimeout(() => {
            const position = menuPositions.value[e];
            scrollTop.value = position - initTop.value;
        });
    })
};


// 搜索
const c_search = ref('');

// 蒙层
const fadeHeight = ref();
const isPopupVisible = computed(()=> {
    return c_search.value.length > 0;
})

const hidePopup = () => {
  c_search.value = '';
}

onLoad(() => {
    uni.hideTabBar();
    GetMyMenu()
})

onShow(() => {
    initScrollView()
})

/**
 * 滚动
 */
const popupHeight = ref('');
const initScrollView =() => {
    setTimeout(() => {
        uni.getSystemInfo({
            success: (res) => {
                const screenWidth:number = res.screenWidth;
                const query = uni.createSelectorQuery().in(this);
                query.select('.mask-box').boundingClientRect((data: any) => {
                    const inputPaddingBottom =(screenWidth * Number.parseInt('29')) / 750;
                    const number = data?.top - inputPaddingBottom;
                    fadeHeight.value = res.windowHeight - number;
                }).exec();

                query.select('.home-content').boundingClientRect((data: any) => {
                    let tabBarHeight:number = (screenWidth * Number.parseInt('118')) / 750;
                    scrollHeight.value = (res.windowHeight - data?.top - tabBarHeight);
                }).exec();
            }
        })
    }, 1000)
}

// 获取所有 menu-module 元素的距离顶部的距离
const menuPositions = ref<number[]>([]);
const getMenuModulePositions = () => {
    const query = uni.createSelectorQuery().in(uni.$u);
    query.selectAll('.menu-module').boundingClientRect((data) => {
        data.forEach((item, index) => {
            if (index === 0) {
                initTop.value = item?.top
            }
            // console.log(`元素距离页面顶部的距离: ${item.top}px`);
            menuPositions.value.push(item?.top)
        });
    })
    .exec();
};
const threshold = 50;  // 设置上下浮动的阈值
const findClosestIndex = (value:number) => {
    let low = 0;
    let high = menuPositions.value.length - 1;

    while (low <= high) {
        const mid = Math.floor((low + high) / 2);
        const midValue = menuPositions.value[mid];

        if (Math.abs(midValue - value) <= threshold) {
            return mid;
        } else if (midValue < value) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    // 如果没有精确匹配，返回最接近的值的索引
    return Math.abs(menuPositions.value[low] - value) < Math.abs(menuPositions.value[high] - value) ? low : high;
};

const onScroll = (event) => {
    toggleFixed.value = false;
    const scrollTop = event.detail.scrollTop + initTop.value;
    const closestIndex = findClosestIndex(scrollTop);
    industryTabIndex.value = closestIndex;

}
// 使用节流函数
const throttle = (func, limit) => {
    let lastRan;
    let lastFunc;
    return function() {
        const context = this;
        const args = arguments;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            if (Date.now() - lastRan >= limit) {
                func.apply(context, args);
                lastRan = Date.now();
            } else {
                clearTimeout(lastFunc);
                lastFunc = setTimeout(() => {
                func.apply(context, args);
                lastRan = Date.now();
                }, limit - (Date.now() - lastRan));
            }
        }
    };
};

const throttledScroll = throttle(onScroll, 100);
/**
 * 菜单相关
 */
 type Menu = {
    c_menu_code?: string,
    c_menu_title?: string,
    c_mdcode?: string,
    c_type?: string,
    c_md_name?: string,
    c_md_cname?: string,
    c_file?: string,
    c_client_type?: string,
    c_function_type?: string,
    c_origin_type?: string,
    c_status?: string,
    c_version?: string,
    c_limitcode?: string,
    c_ini_param?: string,
    c_menu_extend?: string,
    c_menu_img?: string,
    c_system?: string,
    c_start_color?: string,
    c_end_color?: string,
}
const menuList = ref([]);
const menuData = ref([]);

// 获取菜单列表
const moduleDataStore = useModuleDataStore();
const GetMyMenu = () => {
    const baseUrl = '../../../static/img/apply';
    tabData.value = [];
    const ObjectData = moduleDataStore.MenusAndLimitCode;
    let menu = [];
    if (ObjectData.length > 0) {
        menu = ObjectData.filter(item => item.c_mdcode).map( item => ({
            ...item,
            c_start_color: item.c_start_color ? hexToRgb(item.c_start_color) : 'rgba(1, 126, 255, 0.05)',
            c_menu_img: item.c_menu_img ? `${baseUrl}/${item.c_menu_img}.png` : `${baseUrl}/apply_bg_qtjl.png`,
        }));

        const newArray = ObjectData.filter(item => item.c_mdcode === "" || item.c_mdcode === null).map(item => ({
            c_menu_code: item.c_menu_code,
            c_menu_title: item.c_menu_title,
            expandmodel: ObjectData.length > 8, // 这里假设你想要基于原始数组的长度来决定expandmodel的值
            slideupmenu: false,
            modelsTop: [], // 这里假设models数组为空
            modelsBottom: [], // 这里假设models数组为空
        }));

        newArray.forEach(item => {
            ObjectData.map(item1 => {
                if (item1.c_mdcode != "" && item1.c_mdcode != null && item1.c_menu_code != item.c_menu_code
                    && 0 == item1.c_menu_code.indexOf(item.c_menu_code)) {
                        if (item.modelsTop.length < 4) {
                            item.modelsTop.push({
                                ...item1,
                                c_start_color: item1.c_start_color ? hexToRgb(item1.c_start_color) : 'rgba(1, 126, 255, 0.05)',
                                c_menu_img: item1.c_menu_img ? `${baseUrl}/${item1.c_menu_img}.png` : `${baseUrl}/apply_bg_qtjl.png`,
                            })
                        } else {
                            item.modelsBottom.push({
                                ...item1,
                                c_start_color: item1.c_start_color ? hexToRgbToLinear(item1.c_start_color) : 'rgba(1, 126, 255, 0.05)',
                                c_menu_img: item1.c_menu_img ? `${baseUrl}/${item1.c_menu_img}.png` : `${baseUrl}/apply_bg_qtjl.png`,
                            })
                        }
                }
            })
        });

        const filterArray = newArray.filter((item: any) => item.modelsTop.length > 0);
        tabData.value = filterArray.map((item:any) => item.c_menu_title);
        menuList.value = filterArray;
        menuData.value = menu;
        nextTick(() => {
            setTimeout(() => {
                getMenuModulePositions();
            },300)
        });
    }
}

const filterMenuData = computed(() => {
    return menuData.value.filter(item => {
        return item.c_menu_title.includes(c_search.value);
    });
});

const onTapMenu = (item: Menu, flag='') => {
    console.log('点击了item');
    if (flag == 'Quick') {
        c_search.value = '';
    }
    mainStore.limitCodeIn(item.c_limitcode);
    if (item.c_origin_type == "用户定义报表") {
      const url = `/pages/CommonViews/RdsReport/index?c_mdcode=${item.c_mdcode}&c_mdtitle=${item.c_menu_title}`;
      uni.navigateTo({
        url: url
      });
      return;
    }
    let moduleInfo = encodeURIComponent(JSON.stringify(item));
    uni.navigateTo({
        url: `${item.c_md_name}?moduleInfo=${moduleInfo}`
    });
}

// 错误图片默认
const imageError = (item: Menu) => {
    item.c_menu_img = '../../../static/img/apply/apply_bg_qtjl.png';
}

// 刷新
const onClickRefresh = async () => {
  // 清除缓存
  await clearRdsLocalStorage('');
  // 初始化缓存
  await init();
}

defineExpose({
  onClickRefresh
})


const handlePopupMain = (event: MouseEvent) => {
    c_search.value = '';
}

watch(c_search, (newVal) => {
  if (newVal.length > 0) {
    toggleFixed.value = false;
  }
});

</script>

<style scoped lang="scss">
.icon-zhankai {
    font-size: 24rpx;
    color: #000000;
}
.iconfontColor {
    color: var(--theme-color)
}

.search-view {
    margin-top: 7px;
    ::v-deep .uni-searchbar-content {
        padding-left: 14px !important;
        padding-right: 14px !important;
    }
    ::v-deep .all-box{
        position: absolute;
        top: 88rpx;
    }
}
.menu-module {
    margin: 28rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 32rpx;
    color: #000000;

}

.menu-row-top {
    padding: 0 28rpx 16rpx;
    width: 100%;
    flex-wrap: wrap;
    box-sizing: border-box;
    // gap: 12px;
    display: flex;
    justify-content: space-between;
    .menu-item {
        flex: 0 0 48.5%;
        margin-bottom: 20rpx;
    }
    .menu-row-2 {
        padding: 0 20rpx;
        height: 120rpx;
        align-items: center;
        border-radius: 20rpx;
        box-sizing: border-box;
        .img-box {
            margin-right: 16rpx;
            width: 64rpx;
            height: 64rpx;
        }
        image {
            width: 100%;
            height: 100%;
        }
        .right-box {
            width: 0;
            flex: 1;
        }
        .title {
            font-size: 24rpx;
            color: $enjoy-color-title;
            font-weight: 500;
            font-family: PingFangSC, PingFang SC;
        }
        .description {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 20rpx;
            color: #888888;
        }
    }
}
.menu-row-bottom {
    margin: 0 16rpx 24rpx;
    width: calc(100% - 32rpx);
    .img-box {
        margin-bottom: 8rpx;
        width: 88rpx;
        height: 88rpx;
        border-radius: 32rpx;
        .image {
            width: 64rpx;
            height: 64rpx;
        }
    }
    .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 24rpx;
        color: #000000;
        text-align: center;
    }
}

// 蒙层
/* 淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.mask-box {
    position: relative;
    .fade-popup {
        position: absolute;
        background: rgba(0, 0, 0, 0.5);
        width: 100%;
        height: 200px;
        z-index: 990;
    }
    .search-popup-main {
        padding-top: 5px;
        box-sizing: border-box;
    }
    .search-card {
        min-height: 100rpx;
        margin-top: 10rpx;
    }
    .tips {
        margin-left: 40rpx;
        color: var(--theme-color);
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: 400;
        font-size: 24rpx;
    }
    .note-data-tips {
        height: 100rpx;
        line-height: 100rpx;
    }
}

</style>
